package cn.easyplatform.studio.web.controller;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.identity.GetSMSCmd;
import cn.easyplatform.studio.cmd.identity.GetStudioRetrieveCmd;
import cn.easyplatform.studio.cmd.identity.GetStudioRetrieveSMSCmd;
import cn.easyplatform.studio.utils.StringUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.SMSVo;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zk.ui.util.ComposerExt;
import org.zkoss.zul.*;
import org.zkoss.zul.theme.Themes;

public class RetrievePasswordController implements Composer<Component>, ComposerExt<Component>, EventListener<Event> {

    private enum RetrieveType {
        RetrieveTypeFirstStep,
        RetrieveTypeSecondStep
    }

    private Component parentComponent;

    private Textbox mobile;

    private Textbox verification;

    private Textbox password;

    private Textbox doublePassword;

    private A verificationA;

    private Button submit;

    private Div mobileDiv;

    private Div codeDiv;

    private Div passwordDiv;

    private Div secondPasswordDiv;

    private Timer timer;

    private int count = 60;

    private RetrieveType retrieveType;
    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().equals(timer)) {
            count--;
            if (count > 0) {
                verificationA.setLabel(count + "s");
                verificationA.setDisabled(true);
            } else {
                timer.stop();
                verificationA.setLabel(Labels.getLabel("register.verification.get"));
                verificationA.setDisabled(false);
                count = 60;
            }
        } else if ("retrieve_verification_a".equals(event.getTarget().getId())) {
            if (Strings.isBlank(mobile.getText()) ||
                    StringUtil.regexString(mobile.getText(), StringUtil.RegexType.RegexIsMobile) == false)
                throw new WrongValueException(mobile, Labels
                        .getLabel("register.phone.placeholder"));
            Boolean isSuccess = StudioApp.execute(new GetSMSCmd(mobile.getText(), SMSVo.SMSType.SMSRetrieve));
            if (isSuccess == true) {
                timer = new Timer();
                timer.setDelay(1000);
                event.getTarget().getParent().appendChild(timer);
                timer.addEventListener(Events.ON_TIMER, this);
                timer.setRepeats(true);
                timer.start();
            }
        } else if ("retrieve_login".equals(event.getTarget().getId())) {
            Include include = (Include) parentComponent.getRoot();
            include.setSrc("~./include/login/login1.zul");
        } else if ("retrieve_next".equals(event.getTarget().getId())) {
            if (retrieveType == RetrieveType.RetrieveTypeFirstStep) {
                if (Strings.isBlank(mobile.getText()) ||
                        StringUtil.regexString(mobile.getText(), StringUtil.RegexType.RegexIsMobile) == false)
                    throw new WrongValueException(mobile, Labels
                            .getLabel("register.phone.placeholder"));
                if (Strings.isBlank(verification.getText()) ||
                        StringUtil.regexString(verification.getText(), StringUtil.RegexType.RegexIsVerification) == false)
                    throw new WrongValueException(verification, Labels
                            .getLabel("register.verification.input.placeholder"));

                Boolean isSuccess = StudioApp.execute(new GetStudioRetrieveSMSCmd(
                        mobile.getText().trim(), verification.getText().trim()));
                if (isSuccess) {
                    retrieveType = RetrieveType.RetrieveTypeSecondStep;
                    mobileDiv.setVisible(false);
                    codeDiv.setVisible(false);
                    passwordDiv.setVisible(true);
                    secondPasswordDiv.setVisible(true);
                    submit.setLabel(Labels.getLabel("forget.password.finish"));
                }
            } else {
                if (Strings.isBlank(password.getText()) ||
                        StringUtil.regexString(password.getText(), StringUtil.RegexType.RegexIsPassword) == false)
                    throw new WrongValueException(password, Labels
                            .getLabel("constraint.password"));
                if (Strings.isBlank(doublePassword.getText()) ||
                        StringUtil.regexString(doublePassword.getText(), StringUtil.RegexType.RegexIsPassword) == false)
                    throw new WrongValueException(doublePassword, Labels
                            .getLabel("constraint.password"));
                if (password.getText().equals(doublePassword.getText()) == false)
                    throw new WrongValueException(doublePassword, Labels
                            .getLabel("constraint.no.equal.password"));

                Boolean isSuccess = StudioApp.execute(new GetStudioRetrieveCmd(
                        mobile.getText().trim(), password.getText().trim()));
                if (isSuccess) {
                    retrieveType = RetrieveType.RetrieveTypeFirstStep;
                    WebUtils.showSuccess(Labels.getLabel("forget.finish.login"));
                    Include include = (Include) parentComponent.getRoot();
                    include.setSrc("~./include/login/login1.zul");
                }
            }
        }
    }

    @Override
    public void doAfterCompose(Component component) throws Exception {
        parentComponent = component;
        submit = (Button) component.query("#retrieve_next");
        submit.addEventListener(Events.ON_CLICK, this);
        mobile = (Textbox) component.query("#retrieve_mobile");
        verification = (Textbox) component.query("#retrieve_verification");
        password = (Textbox) component.query("#retrieve_password");
        doublePassword = (Textbox) component.query("#retrieve_password_double");

        StringBuilder sb = new StringBuilder();
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(verification.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("register.phone.placeholder"))
                .append("')");
        mobile.setWidgetListener(Events.ON_OK, sb.toString());
        mobile.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +mobile.getId() +"')).val().length!=0){jq(zk.$('$" +verification.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(submit.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("register.verification.input.placeholder"))
                .append("')");
        verification.setWidgetListener(Events.ON_OK, sb.toString());
        verification.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +verification.getId() +"')).val().length!=0){jq(zk.$('$" +submit.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(doublePassword.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("constraint.password"))
                .append("')");
        password.setWidgetListener(Events.ON_OK, sb.toString());
        password.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +password.getId() +"')).val().length!=0){jq(zk.$('$" +doublePassword.getId() +"')).focus();}");

        sb.setLength(0);
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(submit.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("constraint.password"))
                .append("')");
        doublePassword.setWidgetListener(Events.ON_OK, sb.toString());
        doublePassword.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +doublePassword.getId() +"')).val().length!=0){jq(zk.$('$" +submit.getId() +"')).focus();}");

        verificationA = (A) component.query("#retrieve_verification_a");
        verificationA.addEventListener(Events.ON_CLICK, this);
        component.query("#retrieve_login").addEventListener(Events.ON_CLICK, this);
        mobileDiv = (Div) component.query("#retrieve_div_mobile");
        codeDiv = (Div) component.query("#retrieve_div_code");
        passwordDiv = (Div) component.query("#retrieve_div_password");
        secondPasswordDiv = (Div) component.query("#retrieve_div_secondPassword");
        retrieveType = RetrieveType.RetrieveTypeFirstStep;
    }

    @Override
    public ComponentInfo doBeforeCompose(Page page, Component component, ComponentInfo componentInfo) throws Exception {
        Themes.setTheme(Executions.getCurrent(), "atrovirens_c");
        component.addEventListener(Events.ON_OK, new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
                Events.postEvent(new Event(Events.ON_CLICK, submit));
            }
        });
        return componentInfo;
    }

    @Override
    public void doBeforeComposeChildren(Component component) throws Exception {

    }

    @Override
    public boolean doCatch(Throwable throwable) throws Exception {
        return false;
    }

    @Override
    public void doFinally() throws Exception {

    }
}
